<template>
  <div class="container-header table-search">
    <Button v-if="searchOption.showBackBtn" size="large" class="fl btn-back mr10" icon="ios-arrow-back" @click="clickBackFn">返回</Button>
    <div
      v-if="searchOption.showMonth ? searchOption.showMonth.value : false"
      class="item"
      :class="{ 'item-special': Object.keys(searchOption).length < 4, 'table-item': Object.keys(searchOption).length >= 4}"
    >
      <span class="label">月份:</span>
      <DatePicker
        v-model="searchCondition.useMonth"
        class="content"
        type="month"
        placement="bottom-end"
        placeholder="月份"
      />
    </div>

    <div
      v-if="searchOption.showStoreName ? searchOption.showStoreName.value : false"
      class="item"
      :class="{ 'item-special': Object.keys(searchOption).length < 4, 'table-item': Object.keys(searchOption).length >= 4}"
    >
      <span class="label">门店:</span>
      <Select
        ref="storeSelect"
        v-model="searchCondition.storeId"
        class="content"
        clearable
        :remote-method="storeRemoteMethod"
        placeholder="请输入门店名称"
        remote
        filterable
        :loading="storeSelectLoading"
      >
        <Option v-for="item in storeList" :key="item.value" :value="item.value">{{ item.label }}</Option>
      </Select>
    </div>

    <!-- 以优惠券名称搜索 -->
    <div
      v-if="searchOption.showCouponName ? searchOption.showCouponName.value : false"
      class="item"
      :class="{ 'item-special': Object.keys(searchOption).length < 4, 'table-item': Object.keys(searchOption).length >= 4}"
    >
      <span class="label">优惠券名称:</span>
      <Input v-model="searchCondition.couponName" class="content" clearable :placeholder="searchOption.showCouponName.placeholder || '优惠券名称'" @on-enter="onSearchBtnClick" />
    </div>
    <!-- 以优惠券id搜索 -->
    <div
      v-if="searchOption.showCouponId ? searchOption.showCouponId.value : false"
      class="item"
      :class="{ 'item-special': Object.keys(searchOption).length < 4, 'table-item': Object.keys(searchOption).length >= 4}"
    >
      <span class="label">优惠券名称:</span>
      <Select
        ref="couponSelect"
        v-model="searchCondition.couponId"
        class="content"
        clearable
        :remote-method="couponRemoteMethod"
        placeholder="请输入优惠券名称"
        remote
        filterable
        :loading="couponSelectLoading"
      >
        <Option v-for="item in couponList" :key="item.value" :value="item.value">{{ item.label }}</Option>
      </Select>
    </div>

    <div
      v-if="searchOption.showKeyword ? searchOption.showKeyword.value : false"
      class="item"
      :class="{ 'item-special': Object.keys(searchOption).length < 4, 'table-item': Object.keys(searchOption).length >= 4}"
    >
      <span class="label">关键字:</span>
      <Input v-model="searchCondition.keyword" class="content" clearable :placeholder="searchOption.showKeyword.placeholder || '领取人 / 分享人手机号'" @on-enter="onSearchBtnClick" />
    </div>

    <div
      v-if="searchOption.showStatus ? searchOption.showStatus.value : false"
      class="item"
      style="flex: 0.6"
      :class="{ 'item-special': Object.keys(searchOption).length < 4, 'table-item': Object.keys(searchOption).length >= 4}"
    >
      <span class="label">状态筛选:</span>
      <Select v-model="searchCondition.status" class="content" clearable :placeholder="searchOption.showStatus.placeholder || '状态筛选'">
        <Option v-for="item in statusMap" :key="item.value" :value="item.value">{{ item.label }}</Option>
      </Select>
    </div>

    <div
      v-if="searchOption.showSelect ? searchOption.showSelect.value : false"
      class="item"
      :class="{ 'item-special': Object.keys(searchOption).length < 4, 'table-item': Object.keys(searchOption).length >= 4}"
    >
      <Select v-model="chooseSelectOption" clearable style="width:110px" @on-change="onSelectChange" class="start">
        <Option v-for="item in selects" :key="item.value" :value="item.value">{{ item.label }}</Option>
      </Select>
      <Input v-model="chooseSelectValue" class="start-input content" :disabled="btnDisabled" clearable :placeholder="searchOption.showSelect.placeholder || '领取人 / 分享人手机号'" @change="onSelectInputChange" @on-enter="onSearchBtnClick" />
    </div>

    <div
      v-if=" searchOption.showDate ? searchOption.showDate.value : false"
      class="item"
      :class="{ 'item-special': Object.keys(searchOption).length < 4, 'table-item': Object.keys(searchOption).length >= 4}"
    >
      <span class="label">选择时间:</span>
      <DatePicker v-model="date" class="content" type="daterange" placement="bottom-start" :placeholder="searchOption.showDate.placeholder || '选择日期'" />
    </div>

    <Button class="btn-search mr" type="primary" icon="ios-search" @click="onSearchBtnClick" />
    <export-btn v-show="searchOption.showExport" @onExport="onExport" size="default"></export-btn>
  </div>
</template>
<script>
import { clearEmpty } from '@/util'
import moment from 'moment'
export default {
  props: {
    searchOption: {
      type: Object,
      default: () => {}
    },
    clickBackFn: {
      type: Function
    },
    value: {
      type: Object
    }
  },
  data () {
    return {
      selects: [
        { value: 'useOrderSn', label: '券使用订单号' },
        { value: 'barCode', label: '已入库条码' },
        { value: 'sendOrderSn', label: '送券订单号' },
        { value: 'couponCode', label: '优惠券码' }
      ],
      statusMap: [
        { value: 10, label: '待激活' },
        { value: 11, label: '可使用' },
        { value: 12, label: '已使用' },
        { value: 13, label: '已作废' },
        { value: 14, label: '已过期' }
      ],
      searchCondition: {
        couponName: '',
        keyword: '',
        status: '',
        useMonth: ''
      },
      date: [],
      chooseSelectOption: '',
      chooseSelectValue: '',
      storeList: [],
      couponList: [],
      queryStoreName: '',
      queryCouponName: '',
      storePages: 0,
      storeCurrent: 1,
      couponPages: 0,
      couponCurrent: 1,
      btnDisabled: true
    }
  },
  watch: {
    chooseSelectOption (val) {
      if (!val) {
        this.btnDisabled = true
      } else {
        this.btnDisabled = false
      }
    }
  },
  created () {
    Object.keys(this.value).forEach(key => {
      if (['couponName', 'keyword', 'status', 'useMonth'].indexOf(key) >= 0) {
        if (this.value[key]) this.searchCondition[key] = this.value[key]
      } else {
        if (this.value.startDate) this.date[0] = new Date(moment(this.value.startDate))
        if (this.value.endDate) this.date[1] = new Date(moment(this.value.endDate))
      }
    })
    if (this.searchOption.showMonth) {
      const now = new Date()
      const nowYear = now.getFullYear()
      const nowMonth = now.getMonth()
      let lastMonth = nowMonth === 0 ? 12 : nowMonth
      lastMonth = lastMonth.toString().length === 2 ? lastMonth : `0${lastMonth}`
      this.searchCondition.useMonth = `${nowYear}-${lastMonth}`
    } else {
      this.searchCondition.useMonth = ''
    }
  },
  mounted () {
    this.$bus.$on('resetSearch', () => {
      this.resetSearch()
    })
    //监听滚动
    if (this.searchOption.showStoreName && this.searchOption.showStoreName.value) {
      this.$refs.storeSelect.$refs.dropdown.$el.addEventListener('scroll', (e) => {
        if (e.target.scrollTop + e.target.offsetHeight >= e.target.scrollHeight && this.storeCurrent < this.storePages) {
          this.storeCurrent += 1
          this.getStoreData()
        }
      })
    }
    if (this.searchOption.showCouponId && this.searchOption.showCouponId.value) {
      this.$refs.couponSelect.$refs.dropdown.$el.addEventListener('scroll', (e) => {
        if (e.target.scrollTop + e.target.offsetHeight >= e.target.scrollHeight && this.couponCurrent < this.couponPages) {
          this.couponCurrent += 1
          this.getCouponData()
        }
      })
    }
    for (const key in this.searchCondition) {
      if (this.searchCondition[key]) {
        this.onSearchBtnClick()
        break
      }
    }
  },
  methods: {
    onSelectInputChange (e) {
      this.searchCondition[this.chooseSelectOption] = this.chooseSelectValue
    },
    onSelectChange (value) {
      this.chooseSelectOption = value
      this.chooseSelectValue = ''
      this.selects.forEach(item => {
        if (this.searchCondition[item.value]) {
          delete this.searchCondition[item.value]
        }
      })
    },
    handleSearchCondition () {
      if (this.chooseSelectOption) {
        this.searchCondition[this.chooseSelectOption] = this.chooseSelectValue
      }
      if (this.date.length) {
        this.searchCondition.startDate = this.date[0] ? moment(this.date[0]).format('YYYY-MM-DD') : ''
        this.searchCondition.endDate = this.date[1] ? moment(this.date[1]).format('YYYY-MM-DD') : ''
      }
      this.searchCondition = clearEmpty(this.searchCondition)
      return this.searchCondition
    },
    onSearchBtnClick () {
      if (!this.searchOption.showMonth) {
        this.searchCondition.useMonth = ''
      }
      this.handleSearchCondition()
      this.$emit('onSearch', this.searchCondition)
    },
    storeRemoteMethod (query) {
      if (query !== '') {
        this.storeCurrent = 1
        this.storeList = []
        this.storeSelectLoading = true
        this.queryStoreName = query
        this.getStoreData()
      } else {
        this.storeList = []
      }
    },
    getStoreData () {
      const param = {
        current: this.storeCurrent,
        size: 20
      }
      if (this.queryStoreName) param.storeName = this.queryStoreName
      this.$ajaxGet('/tiger/store/page', param).then(res => {
        if (this.storeCurrent === 1) this.storeList = []
        const records = res.records || []
        this.storeSelectLoading = false
        let storeList = []
        storeList = records.map(item => {
          return {
            value: item.storeId,
            label: item.storeName
          }
        })
        this.storeList = [...this.storeList, ...storeList]
        this.storePages = res.pages
      })
    },
    couponRemoteMethod (query) {
      if (query !== '') {
        this.couponCurrent = 1
        this.couponList = []
        this.couponSelectLoading = true
        this.queryCouponName = query
        this.getCouponData()
      } else {
        this.couponList = []
      }
    },
    getCouponData () {
      const param = {
        current: this.couponCurrent,
        size: 20
      }
      if (this.queryCouponName) param.couponName = this.queryCouponName
      this.$ajaxGet('/coupon/coupon_info/page', param).then(res => {
        if (this.couponCurrent === 1) this.couponList = []
        const records = res.records || []
        this.couponSelectLoading = false
        let couponList = []
        couponList = records.map(item => {
          return {
            value: item.id,
            label: item.couponName
          }
        })
        this.couponList = [...this.couponList, ...couponList]
        this.couponPages = res.pages
      })
    },
    resetSearch () {
      Object.keys(this.searchCondition).forEach(key => {
        this.searchCondition[key] = ''
      })
      this.date = []
      this.chooseSelectOption = ''
      this.chooseSelectValue = ''
    },
    onExport () {
      this.handleSearchCondition()
      this.$emit('onExport', this.searchCondition)
    }
  }
}
</script>
